package etnorservice.etnor_service.controller;


import etnorservice.etnor_service.domain.GitAuthConfig;
import etnorservice.etnor_service.emus.AuthType;
import etnorservice.etnor_service.result.ApiResponse;
import etnorservice.etnor_service.service.GitService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
public class GitController {

    private final GitService gitService;

    @PostMapping("/git/branches")
    public ApiResponse<List<String>> getBranches(@RequestBody Map<String, Object> params) {
        try {
            String repoUrl = (String) params.get("repoUrl");
            GitAuthConfig auth = convertAuthConfig(params.get("auth"));
            return ApiResponse.success(gitService.getBranches(repoUrl, auth));
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @PostMapping("/git/test-connection")
    public ApiResponse<Void> testConnection(@RequestBody Map<String, Object> params) {
        try {
            String repoUrl = (String) params.get("repoUrl");
            GitAuthConfig auth = convertAuthConfig(params.get("auth"));
            System.out.println("auth=========>"+auth);
            gitService.testConnection(repoUrl, auth);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    private GitAuthConfig convertAuthConfig(Object authObj) {
        if (authObj == null) {
            return null;
        }

        GitAuthConfig config = new GitAuthConfig();
        @SuppressWarnings("unchecked")
        Map<String, Object> authMap = (Map<String, Object>) authObj;

        // 获取认证类型
        String type = (String) authMap.get("type");
        if (type != null) {
            config.setType(AuthType.valueOf(type.toUpperCase()));
        }

        // 获取配置信息
        @SuppressWarnings("unchecked")
        Map<String, String> configMap = (Map<String, String>) authMap.get("config");
        if (configMap != null) {
            switch (config.getType()) {
                case PASSWORD:
                    config.setUsername(configMap.get("username"));
                    config.setPassword(configMap.get("password"));
                    break;

                case TOKEN:
                    config.setToken(configMap.get("token"));
                    break;

                case SSH:
                    config.setSshKey(configMap.get("sshKey"));
                    config.setPassphrase(configMap.get("passphrase"));
                    break;

                case NONE:
                default:
                    break;
            }
        }

        return config;
    }
}